#! /usr/bin/env python
#coding=utf-8
#-*- coding: UTF-8 -*- 
#coder  poorboy(叼毛)
#url  http://www.caipiao365.vip


import os
import sys
import wx
import re
import json 
import threading
import datetime
import random

sys.path.append("..\\")
sys.path.append("..\\..") 

from utils import commutils
from ui import downThread


class MainPan(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        #默认的线程数量
        self.nThredNumber  = 5 
        
        #默认的视频保存路径
        self.strSavePath = "F:\\vDown\\"
        #默认文件存在跳过不下载
        self.bIsOver = False

        #获取的视频信息保存的数组
        self.Vitems = []

        #下载视频线程完成的数量
        self.FinshNumber = 0 

        #下载视频线程完成的数组
        self.FinshTid = []

        #下载视频的个数
        self.DownCount = 0

        #下载视频成功的个数
        self.DownSuccessCount = 0

        self.bIsGetVItemInfo = False
        self.bIsDownVItem = False

        self.startTime = datetime.datetime.now() 
        self.timer = wx.Timer(self)#创建定时器

        self._init_ctrls()  

        self.Layout()
        self.Centre()
        self.Show(True) 
        
    #初始化界面控价
    def _init_ctrls(self):
        
        self.txtSavePath = wx.TextCtrl(self, -1, self.strSavePath, style=wx.TE_READONLY)  
        self.bntGetPath = wx.Button(self, -1, u'选择目录', size=(80, 30)) 

        self.bntQurey = wx.Button(self, -1, u'下载', size=(80, 30)) 
        self.txtSearchKey = wx.TextCtrl(self, -1, "儿童舞蹈教学")
        

        self.rbSkip = wx.RadioButton(self, label='跳过', style=wx.RB_GROUP, size=(50, 20))
        self.rbOver = wx.RadioButton(self, label=u'覆盖', size=(50, 20)) 
        
        
        threadNumber = ['1', '2', '3', '4', '5', '10', '15', '20', '25', '30', '40', '50']       
        self.cbThredNumber = wx.ComboBox(self, -1, "5", (15, 30), wx.DefaultSize, threadNumber, wx.CB_READONLY)

        self.txtPageSize = wx.TextCtrl(self, -1, "100")

        self.log = wx.TextCtrl(self, -1, '', style = wx.TE_RICH | wx.TE_MULTILINE|wx.TE_READONLY)
        self.tc = wx.StaticText(self, -1, u"")
        self.txtSavePath.Enable(False)

    #初始化界面控价布局   
    def Layout(self):
        self.sizer = wx.BoxSizer(wx.VERTICAL) 

        h0 = wx.BoxSizer(wx.HORIZONTAL)
        h0.Add(wx.StaticText(self, 0, u'文件保存的路径: '))
        h0.Add(self.txtSavePath, 1)
        h0.Add(self.bntGetPath, 0) 
        self.sizer.Add(h0, 0, wx.EXPAND | wx.ALL, 2)
        
        h1 = wx.BoxSizer(wx.HORIZONTAL)
        h1.Add(wx.StaticText(self, 0, u'搜索关键词: '))
        h1.Add(self.txtSearchKey, 1)
        h1.Add(wx.StaticText(self, 0, u'获取前面多少条视频: '))
        h1.Add(self.txtPageSize, 0)   
        h1.Add(self.bntQurey, 0) 
        self.sizer.Add(h1, 0, wx.EXPAND | wx.ALL, 2)
        
        h2 = wx.BoxSizer(wx.HORIZONTAL)
        h2.Add(wx.StaticText(self, 0, u'相同文件操作方式: '))
        h2.Add(self.rbSkip, 0)
        h2.Add(self.rbOver, 0) 
        h2.Add(wx.StaticText(self, 0, u'启动多少条线程(电脑性能越好可以设置大一点): '))
        h2.Add(self.cbThredNumber, 0)
        self.sizer.Add(h2, 0, wx.EXPAND | wx.ALL, 2)
        
     
        
        self.sizer.Add(self.log, 1, wx.EXPAND) 
        self.sizer.Add(self.tc, 0, wx.EXPAND) 
        
        self.BindEvent()
        self.SetSizer(self.sizer)
        self.Centre()
        self.Show(True)
    
    #控件绑定事件
    def BindEvent(self):
        self.bntQurey.Bind(wx.EVT_BUTTON, self.OnButQuery) 
        self.bntGetPath.Bind(wx.EVT_BUTTON, self.OnGetSaveDir)
        self.Bind(wx.EVT_TEXT, self.EvtThradNumber, self.cbThredNumber)
        
        self.rbOver.Bind(wx.EVT_RADIOBUTTON, self.SetVal)
        self.rbSkip.Bind(wx.EVT_RADIOBUTTON, self.SetVal) 

        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

    #时间处理方法
    def OnTimer(self, evt):
        timespan = datetime.datetime.now() - self.startTime 
        countTime = int(timespan.total_seconds())
        if self.bIsGetVItemInfo :
            self.tc.SetLabel(u"一花{0},正在获取搜索的结果".format(commutils.FormatTimeStr(countTime)))
        elif self.bIsDownVItem :
            self.tc.SetLabel(u"一花{0},一共下载了{1}/{2}个视频,成功了{3}个,线程信息{4}/{5}".format(
                commutils.FormatTimeStr(countTime), 
                self.DownCount, 
                len(self.Vitems), 
                self.DownSuccessCount,
                self.FinshNumber,
                self.nThredNumber
                ))

    #日志处理方法
    def LogMessage(self, msg):
        self.log.AppendText(msg)
    
    #日志处理方法
    def LogMessageLn(self, msg):
        self.LogMessage(msg)
        self.LogMessage("\r\n")

    #获取搜索视频信息线程通知主界面视频信息增加的方法
    def AddVItems(self, items): 
        for tItem in items:
            self.Vitems.append(tItem)

    #视频下载后播放的提示声音
    def PlaySound(self):
        try:
            sound = wx.Sound(u'res/downFinsh.wav')
            if sound.IsOk():
                sound.Play(wx.SOUND_ASYNC)
            else:
                self.LogMessageLn(u"播放声音文件失败")
        except Exception as e:
            self.LogMessageLn(u"播放声音文件失败")
            print e

    #当关闭主界面时调用的方法
    def OnCloseWindow(self, e):
        self.Destroy()
    
    #文件单选框  覆盖 和跳过的 事件处理方法
    def SetVal(self, e):
        self.bIsOver = self.rbOver.GetValue()

    #单击下载按钮的事件处理方法
    def OnButQuery(self, e): 
        strKey = self.txtSearchKey.GetValue()
        if strKey == None or len(strKey) < 2:
            return
 
        if( self.nThredNumber < 1):
            self.nThredNumber = 1
        
        if( self.nThredNumber > 50):
            self.nThredNumber = 50

        #self.SerchKey = commutils.GetUtf8Str(strKey)
        self.SerchKey = "儿童舞蹈教学" #strKey.encode("gbk")

        pageSize = self.txtPageSize.GetValue();
        self.nPageSize = int(pageSize)

        if(self.nPageSize < 20):
            self.nPageSize = 20  

        self.startTime = datetime.datetime.now()  
        self.Vitems = []

        thread = downThread.GetVideoItemsThread(self)
        thread.start()
        self.EanbleUI(False)

        self.bIsDownVItem = False
        self.bIsGetVItemInfo = True 

        self.timer.Start(1000) 
    
    #当获取搜索信息线程完成后调用的方法
    def GetVoideItemsThreadFinsh(self): 
        self.LogMessageLn(u'获取视频信息完成，一共获取了:[{0}]条'.format(len(self.Vitems)))
        self.FinshNumber = 0 
        self.FinshTid = []
        self.DownCount = 0
        self.DownSuccessCount = 0
        
        self.bIsDownVItem = True 
        self.bIsGetVItemInfo = False

        for i in range(0, self.nThredNumber):  
            thDown = downThread.DownVideoThread(self, i + 1)
            thDown.start()

    def DownItemFinsh(self, tID, bIsSuccess):
        self.DownCount = self.DownCount + 1  
        if bIsSuccess:
            self.DownSuccessCount = self.DownSuccessCount + 1  
        
    #当下载视频线程完成后调用的方法
    def DownThreadFinsh(self, tID, nDownCount, nSuccessCount): 
        self.FinshNumber =  self.FinshNumber  + 1
        self.FinshTid.append(tID)
        srtInfo = u'' 

        if self.FinshNumber == self.nThredNumber:
            self.timer.Stop() 
            timespan = datetime.datetime.now() - self.startTime 
            countTime = int(timespan.total_seconds())
            info = u"所有线程执行完成,一花{0},一共查了下载了{1}个视频，成功了{2}".format(commutils.FormatTimeStr(countTime), self.DownCount, self.DownSuccessCount)
            self.LogMessageLn(info)
            self.tc.SetLabel(info)
            self.EanbleUI(True)
            self.PlaySound()
        else: 
            srtInfo = u'线程[{0}]执行完成,一共下载了：{1} 个视频，成功了：{2}个 '.format(tID, nDownCount, nSuccessCount)
            self.LogMessageLn(srtInfo) 

    #当单击或选择目录按钮调用的事件方法
    def OnGetSaveDir(self, event): 
        dlg = wx.DirDialog(self, 
                            u"视频保存的目录", 
                            self.strSavePath, 
                            wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
        if dlg.ShowModal() == wx.ID_OK:
            bRet = True
            self.strSavePath = dlg.GetPath() + "\\"
            self.txtSavePath.SetValue(self.strSavePath )
            self.LogMessageLn(u'设置视频文件保存目录:[{0}]'.format(self.strSavePath))
        dlg.Destroy()

    #当改变界面上线程数量下拉框处理的事件方法
    def EvtThradNumber(self, evt):
        self.nThredNumber = int(evt.GetString())        
        evt.Skip()

    #当线程运行后要禁用的按钮等控件的方法    
    def EanbleUI(self, bIsEanble):
        self.bntQurey.Enable(bIsEanble)
        self.bntGetPath.Enable(bIsEanble) 
        self.txtSearchKey.Enable(bIsEanble)
        self.rbSkip.Enable(bIsEanble)
        self.rbOver.Enable(bIsEanble)      
        self.cbThredNumber.Enable(bIsEanble)
        self.txtPageSize.Enable(bIsEanble)
        #self.log.Enable(bIsEanble)
        
        
        
class TestUi(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, u' ', size=(700, 500))
        p1 = MainPan(self)
        sizer = wx.BoxSizer()
        sizer.Add(p1, 1, wx.EXPAND)
        self.SetSizer(sizer)
        self.Centre()
        self.Show(True)


if __name__ == "__main__":
    app = wx.App()
    TestUi().Show()
    app.MainLoop()
